package com.example.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @description shiro 权限Controller
 */
@Controller
public class AuthController {

    /**
     * @description shiro 登陆页面入口
     */
    @RequestMapping("/login")
    public String loginPage() {
        return "/login";
    }

    /**
     * @description shiro 首页入口
     */
    @RequestMapping("/index")
    public String indexPage() {
        return "/index";
    }

    /**
     * @description shiro 登陆操作
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public ModelAndView doLogin(HttpServletRequest request) {
        // 1、获取前端传的 用户名，密码
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        // 2、获取 UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            // 3、shiro登录，执行完 .login() 进入自定义realm
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);

            // 4、登陆成功，重定向到 index 首页
            return new ModelAndView("redirect:/index");
        } catch (AuthenticationException e) {  //登录失败
            ModelAndView mv = new ModelAndView("/login");
            return mv;
        }
    }

    /**
     * @description 退出操作
     */
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //session.removeAttribute("user");
        return "login";
    }

}
